#include <iostream>
#include <string>
#include "searcher.hpp"
#include "cpp-httplib/httplib.h"


const std::string input = "data/raw_html/raw.txt";
const std::string root_path = "./wwwroot";

int main()
{
    ns_searcher::Searcher search;
    search.InitSearcher(input);

    httplib::Server server;
    server.set_base_dir(root_path.c_str());

    server.Get("/search", [&search](const httplib::Request& req, httplib::Response& rsp) {
        if (!req.has_param("wd"))
        {
            rsp.set_content("请输入搜索关键字", "text/plain; charset=utf-8");
        }
        else 
        {
            std::string query = req.get_param_value("wd");
            std::string json_string;
            search.Search(query, &json_string);
    
            rsp.set_content(json_string, "application/json; charset=utf8");
        }
        
    });

    server.Post("/ad_click", [&search](const httplib::Request& req, httplib::Response& rsp) {
        if (req.has_param("doc_id"))
        {
            rsp.status = 400; // bad request
            rsp.set_content("Bad Request", "text/plain; charset=utf8");
        }
        else
        {
            std::string doc_id = req.get_param_value("doc_id");
            uint64_t id = std::stoi(doc_id);
            search.HandleAdClick(id);
            rsp.set_content("{\"status\":\"success\"}", "application/json");
        }
    });

    server.listen("0.0.0.0", 8080);
    return 0;
}
